package com.szsfm.vehiclemanagement.tcp;

import android.text.TextUtils;

import com.orhanobut.logger.Logger;
import com.szsfm.vehiclemanagement.tcp.TcpCore.Packet;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by zhoubigbo on 2017/11/24.
 */
public class Resend {

    private static final int DEF_TIME_OUT = 3000;
    private static final int MAX_RESEND_COUNT = 3;

    private Timer timer;
    private static Map<String, Resend> map = new HashMap<>();

    private static Map<String, Integer> count = new HashMap<>();

    public Resend() {
    }

    public void put(final String key, final Packet packet, final TimerDelayListener l) {

        Integer time = count.get(key);
        if (time != null ) {
            count.put(key, ++time);
            Logger.i("重发次数:" + time);
        }
        if (time!=null&&time == MAX_RESEND_COUNT){
            return;
        }
        if (time == null) {
            time = 0;
            count.put(key, time);
        } else {
            if (time > 0) {
                count.put(key, ++time);
            }
        }


        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (l != null) {
                    map.remove(key);
                    l.timeout(packet);
                }
            }
        }, DEF_TIME_OUT);
        map.put(key, this);
    }

    public static int remove(String key) {
        if (TextUtils.isEmpty(key)) return -1;
        Resend resend = map.get(key);
        if (resend != null && resend.timer != null) {
            resend.timer.cancel();
            resend.timer = null;
            return 0;
        }
        return -2;
    }

    public interface TimerDelayListener {
        void timeout(TcpCore.Packet packet);
    }

    public void clear() {
        map.clear();
        count.clear();
    }

}
